<?php
	//require 'FenyePage.class.php';
	
	class SQLHelper {
		private $conn;
		private $host = "localhost";
		private $user = "root";
		private $passwd = "manager";
		private $database = "test";
		
		function __construct(){
			$this->conn = mysqli_connect($this->host, $this->user, $this->passwd);
			if(!$this->conn)
				die("连接失败:".mysqli_error($this->conn));
			mysqli_select_db($this->conn, $this->database)
				or die(mysqli_error($this->conn));
			mysqli_query($this->conn, "set names utf8");
		}
		
		public function exc_dml($sql){
			$b = mysqli_query($this->conn, $sql)
				or	die(mysqli_error($this->conn));
			if(!$b){
				return 0;
			}else{
				if(mysqli_affected_rows($this->conn) > 0){
					return 1;
				}else{
					return 2;
				}
			}
		}
		
		public function exc_dql($sql){
			$res = mysqli_query($this->conn, $sql)
				or	die(mysqli_error($this->conn));
				
			return $res;
		}
		
		//将结果集转存到一个数组中，内存会自动释放数组所占内存
		public function exc_dql2($sql){
			$arr = array();
			$res = mysqli_query($this->conn, $sql)
				or	die(mysqli_error($this->conn));
			$i = 0;
			while($row = mysqli_fetch_assoc($res))
				$arr[$i++] = $row;
			//释放结果集
			mysqli_free_result($res);
			
			return $arr;
		}
		
		public function exc_dql2_first($sql){
			$arr = array();
			$res = mysqli_query($this->conn, $sql)
				or die(mysqli_error($this->conn));
			if($row = mysqli_fetch_assoc($res))
				$arr = $row;
			mysqli_free_result($res);
			
			return $arr;
		}
		//将查询的分页信息保存到$fenyePage对象里
		public function exc_dql_fenye($sql_pageCount, $sql_resArray,FenyePage $fenyePage){
			$res = mysqli_query($this->conn, $sql_pageCount)
				or die(mysqli_error($this->conn));
			if($row = mysqli_fetch_row($res))
				$fenyePage->pageCount=ceil($row[0]/$fenyePage->pageSize);
			mysqli_free_result($res);
			$fenyePage->resArray = $this->exc_dql2($sql_resArray);
		}
		
		public function connect_close(){
			if(!empty($this->conn))
				mysqli_close($this->conn);
		}
	}
